<?php
  require '../../include/library.inc.php';
  require '../../include/admin_login.inc.php';
    
  $page_id = intval($_GET['page_id']);
  $direction_check = intval($_GET['direction']);
  $top = intval($_GET['top']);
  
  if($page_id && ($direction_check == 1 || $direction_check == -1)) {
  	
  	# Get the current order number
  	$sql = "SELECT 
              order_number
            FROM
              pages
            WHERE
              page_id = ".$page_id."
			";
  	$result = query($sql);
    $row = mysql_fetch_assoc($result);
    $old_order_number = $row['order_number'];
    
    # Get the ID of replaced element
  	$sql = "SELECT
  	           page_id
  	        FROM
  	           pages
  	        WHERE
  	           order_number = ".$old_order_number." + (".$_GET['direction'].")
  	         ";
  	$result = query($sql);
  	$row = mysql_fetch_assoc($result);
  	$replaced_page_id = $row['page_id'];
  	 
  	# Move current element one position
    $sql = "UPDATE 
               pages
            SET
              order_number = order_number + (".$_GET['direction'].") 
            WHERE
               page_id = '".$page_id."' 
             ";
    query($sql);
    
    # Move replaced element to currect element's place
    # Update order of replaced element
    $sql = "UPDATE 
               pages
            SET
              order_number = ".$old_order_number." 
            WHERE
               page_id = '".$replaced_page_id."'
             ";
    query($sql);
    
  } elseif ($page_id && $top==1) {
	  
	$sql = 'SELECT MAX(order_number) AS max_order_number FROM pages';
	$row = mysql_fetch_assoc(query($sql));
	$max_order_number = $row['max_order_number'];
	  
	$sql = "SELECT
			  order_number
			FROM
			  pages
			WHERE
			  page_id = '$page_id'
              ";
    query($sql);
	$row = mysql_fetch_assoc(query($sql));
	$order_number = $row['order_number'];
	
	$sql = "UPDATE
              pages
            SET
              order_number = order_number - 1
            WHERE
              order_number > '$order_number'
              ";
    query($sql);
	
	$sql = "UPDATE
              pages
            SET
              order_number = $max_order_number
            WHERE
              page_id = '$page_id'
              ";
    query($sql);
	  
  }
  
  redirect($_SERVER['HTTP_REFERER']);
?>